package com.eportal.service.impl;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eportal.aop.LogAnnotation;
import com.eportal.base.BaseDAO;
import com.eportal.domain.CInstallUnit;
import com.eportal.domain.CRoom;
import com.eportal.domain.PayOrder;
import com.eportal.domain.RedEnvDetail;
import com.eportal.domain.RedEnvMain;
import com.eportal.domain.RoomUser;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TCommunity;
import com.eportal.domain.TKeys;
import com.eportal.domain.TUsers;
import com.eportal.domain.TpayWalletlst;
import com.eportal.domain.TuserWallet;
import com.eportal.domain.User;
import com.eportal.domain.UsersCommunity;
import com.eportal.exception.MdKnownRunTimeException;
import com.eportal.service.CInstallUnitService;
import com.eportal.service.RedEnvService;
import com.eportal.service.TCommunityService;
import com.eportal.service.TKeysService;
import com.eportal.service.TUsersService;
import com.eportal.service.UserWalletService;
import com.eportal.service.UsersCommunityService;
import com.eportal.util.ValidateUtil;
import com.eportal.util.WebUtil;
import com.framework.jqgrid.JqGridPager;

/**
 * 楼栋管理业务逻辑接口实现
 */
@Service("RedEnvService")
public class RedEnvServiceImpl implements RedEnvService {

	private Map<String, Object> result = new HashMap<String, Object>();
	private static Logger log = Logger.getLogger(CInstallUnitServiceImpl.class.getName());
	@Resource(name="dao")
	private BaseDAO dao;
	@Autowired
    private TUsersService tUsersService;
    @Autowired
    private TCommunityService tCommunityService;
    @Autowired
    private TKeysService tKeysService;
    @Autowired
    private UserWalletService userWalletService;


    
    public RedEnvDetail get(Long sid) {
        return (RedEnvDetail) dao.getById(RedEnvDetail.class, sid);
    }
    
    
    public void updateObject(Object entity) throws Exception {
    	dao.update(entity);
	}


	
	public Object getObjectHql(String name,String where) {
		StringBuffer sb = new StringBuffer("from ");
		sb.append(name);
		sb.append(" where ");
		sb.append(where);
	     return  dao.loadObject(sb.toString());
	}
	


	

	
	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }


	@Override
	public List<Map<String, Object> > page(JqGridPager jqGridPager) {
		String sql = "select t1.sid,decode(t1.mainretype,'1','定额红包','2','随机红包') mainretype,t1.rname,t1.effectivedate," +
				"decode(t1.isallday,'1','全天候','0',(case when t1.period1 is  not null and t1.period2 is not null then t1.period1||'和'||t1.period2 when t1.period2 is null then t1.period1 else t1.period2 end)) period,"+
				"t2.receivenum||'/'||t2.totalnum renum," +
				"t2.receiveamount||'/'||decode(substr(t2.totalamount,1,1),'.','0'||t2.totalamount,t2.totalamount) reamount," +
				"decode(t2.envstatus,'1','未领取','2','领取中','3','已领完','4','已下架') envstatus," +
				"decode(t3.issendall,'0','发送部分对象','1','发送全部对象') issendall" +
				" from t_redenvmain t1,t_redenvdetail t2,t_redenvsendlist t3 ";
		return dao.query(sql, jqGridPager);
	}

	@Override
	public List<Map<String, Object> > logList(JqGridPager jqGridPager) {
		String sql = "select (select ta.agtname from t02_agtent ta where ta.agtcode = t1.agtcode) agtname," +
				"(select tc.communityname from t03_community tc where tc.sid = t1.communityid) comname," +
				"(select tl.install_lock_name from t05_locks tl where tl.pid = t3.pid) lockname," +
				"(select tu.tel from t04_users tu where tu.userid = t3.userid) tel," +
				"t3.pid,t1.rname,t3.remoney,to_char(t3.retime,'YYYY-MM-DD HH24:MI:SS') retime " +
				"from t_redenvmain t1,t_redenvdetail t2,t_redenvreceivelog t3 ";
		return dao.query(sql, jqGridPager);
	}

	@Override
	public Map<String, Object> offMethod(Long sid, Sysopt opt) throws Exception {
		// TODO Auto-generated method stub
		String sql = "select t.sid from t_redenvdetail t where t.remainid = "+sid.toString();
		List<Map<String, Object>> list = dao.queryBySql(sql);
		if(list.size()==0){
	   		 result.put("code", 0);
	         result.put("msg", "红包不存在，请刷新");
	         return result;
		}
		for(int i =0;i<list.size();i++){
			Long id = Long.valueOf(String.valueOf(list.get(i).get("sid")));
			RedEnvDetail redEnvDetail = get(id);
			RedEnvMain redEnvMain = (RedEnvMain) dao.getById(RedEnvMain.class, sid);
			String status  = redEnvDetail.getEnvstatus();
			if(!"1".equals(status)&&!"2".equals(status)){
		   		 result.put("code", 0);
		         result.put("msg", "只有未领取和领取中的红包才允许下架");
		         return result;
			}else{
				redEnvDetail.setEnvstatus("4");
					TuserWallet wallet = userWalletService.getOrcreateWallet(opt.getrLevel(), opt.getAgtCode(), opt.getCommunityId());
					float redEnvbalance = redEnvDetail.getTotalamount()-redEnvDetail.getReceiveamount();
					BigDecimal balance = new BigDecimal(String.valueOf(redEnvbalance));
					TpayWalletlst lst = new TpayWalletlst();
					lst.setCredittime(new Timestamp(System.currentTimeMillis()));
					lst.setGeneralsubject("10003");
					lst.setDetailsubject("0");
					lst.setRemark("红包退款:"+redEnvMain.getRname());
					lst.setDebitsidecash(balance);
					lst.setDebitsidesid(wallet.getWid());
					lst.setOptid("SYSTEM");
					lst.setSwid(wallet.getWid().toString());
					lst.setAmount(wallet.getAmount());
					dao.save(lst);
					wallet.setAmount(wallet.getAmount().add(balance));
					updateObject(wallet);
					updateObject(redEnvDetail);
			}
		}
  		 result.put("code", 1);
         result.put("msg", "操作成功");
         return result;
	}
	
	@Override
	public List<Map<String, Object>> detail(Long sid) {
		// TODO Auto-generated method stub
		String sql = "select t1.sid,decode(t1.mainretype,'1','定额红包','2','随机红包') mainretype,t1.rname,t1.effectivedate," +
				"decode(t1.isallday,'1','全天候','0',(case when t1.period1 is  not null and t1.period2 is not null then t1.period1||'和'||t1.period2 when t1.period2 is null then t1.period1 else t1.period2 end)) period,"+
				"t2.totalnum, t2.totalamount,t1.rectimes,t1.adpicture,t1.curl," +
				"decode(t3.issendall,'0','发送部分对象','1','发送全部对象') issendall" +
				" from t_redenvmain t1,t_redenvdetail t2,t_redenvsendlist t3 " +
				"where t1.sid=t2.remainid and t2.sendlistid = t3.sid and t1.sid= '"+sid+"'";
		return dao.queryBySql(sql);
	}
	
	@Override
	public Map<String, Object> addRedEnv(Sysopt opt, String rName, BigDecimal Amount, int totalNum, int reTimes, String effectiveDate, String period1, String period2, String isAllday,
			 String isSendAll, String agentCodes, String communityIds, String buildingIds, String unitIds, String roomIds, String mainReType, String cUrl, String adPicture, String reqPreUrl) {
		// TODO Auto-generated method stub
		try{
			//增加红包主表数据
			String mainCall = "{call P3_REDENV_CREATEMAIN(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}";
			String[] inList = {opt.getAgtCode(),opt.getCommunityId(),mainReType,rName,String.valueOf(reTimes),effectiveDate,period1,period2,isAllday,adPicture,cUrl,opt.getSid().toString(),"1"};
			String[] outList = {"O_RETCODE","O_RETMSG","O_MAINID"};
			Map<String, Object> mainResult = dao.callProcedure(mainCall, inList, outList);
			if("9999".equals((String.valueOf(mainResult.get("O_RETCODE"))))){
				 result.put("code", 0);
		         result.put("msg", "增加红包主表数据失败");
		         return result;
			}
			String mainId = String.valueOf(mainResult.get("O_MAINID"));
			//增加发送对象表数据
			String sendCall = "{call P3_REDENV_CREATESENDLIST(?,?,?,?,?,?,?,?,?)}";
			String[] sendInList = new String[6]; 
			if("1".equals(isSendAll)){
				sendInList = new String[]{"1","","","","",""};
			}else{
				sendInList = new String[]{"0",agentCodes,communityIds,buildingIds,unitIds,roomIds};
			}
				String[] sendOutList = {"O_RETCODE","O_RETMSG","O_LISTID"};
				Map<String, Object> sendResult = dao.callProcedure(sendCall, sendInList, sendOutList);
				if("9999".equals((String.valueOf(sendResult.get("O_RETCODE"))))){
					 result.put("code", 0);
			         result.put("msg", "增加发送对象表数据失败");
			         return result;
				}	
				String listId = String.valueOf(sendResult.get("O_LISTID"));
			//增加红包明细表数据
			String detailCall = "{call P3_REDENV_CREATEDETAIL(?,?,?,?,?,?,?)}";
			String[] detailInList = {mainId,mainReType,String.valueOf(totalNum),String.valueOf(Amount),listId};
			String[] detailOutList = {"O_RETCODE","O_RETMSG"};
			Map<String, Object> detailResult = dao.callProcedure(detailCall, detailInList, detailOutList);
			if("9999".equals((String.valueOf(detailResult.get("O_RETCODE"))))){
				 result.put("code", 0);
		         result.put("msg", "增加红包明细表数据失败");
		         return result;
			}	
			PayOrder payOrder = new PayOrder();
			payOrder.setOrderRelate("R0001");
			payOrder.setOrderRelateId(mainId);
			payOrder.setPstate("1");
			payOrder.setAmount(new BigDecimal(String.valueOf(Amount)));
			payOrder.setCusername(opt.getSid().toString());
			payOrder.setUserType("1");
			payOrder.setCtime(new Timestamp(System.currentTimeMillis()));
			payOrder.setCname("红包:"+rName);
			payOrder.setReturnUrl(reqPreUrl+"admin/redPacket_activeRedenv.action?redEnvId="+mainId);
			payOrder.setNotifyUrl(reqPreUrl+"admin/redPacket_activeRedenvOut.action?redEnvId="+mainId);
			dao.save(payOrder);
		    result.put("code", 1);
            result.put("msg", "操作成功");
            result.put("orderId", payOrder.getSid().toString());
		}catch(Exception e){
			 result.put("code", 0);
	         result.put("msg", "增加红包数据失败");
	         return result;
		}
		return result;
	}


	
	@Override
	public List<Map<String, String>> listBySql(String hql) {
		return dao.queryBySql(hql);
	}
	
	
	public List<Map<String, Object>> getRoom(String unitId, String roomNo) {
		StringBuilder sql = new StringBuilder("select t.sid,t.room_no as roomno,t.floor_no as floorno from T035_ROOM t where t.unit_id='");
		sql.append(unitId);
		sql.append("' and t.room_no ='");
		sql.append(roomNo);
		sql.append("'");
		return dao.queryBySql(sql.toString());
	}

	@Override
	public List<Map<String, Object>> queryBySql(String unit, String budingid) {
		StringBuffer sql = new StringBuffer();
		
		sql.append("select t.userid,u.tel as usertel,u.auname as username from t04_users_community t  left join t04_users u on t.userid=u.userid where ");
		if (StringUtils.isNotBlank(unit)) {
			sql.append(" t.installunitid in(");
			sql.append(unit);
			sql.append(")");
		}else{
			sql.append(" t.cbuildingId=");
			sql.append(budingid);
		}
		return dao.queryBySql(sql.toString());
	}


	//激活红包
	@Override
	public Map<String, Object> activeRedenv(String redEnvId) {
		// TODO Auto-generated method stub
    	result = new HashMap<String, Object>();
		List<Map<String, Object>> list = dao.queryBySql("select PSTATE from t_pay_order where ORDER_RELATE_ID = '"+redEnvId+"'");
		if(list.size()==0){
			 result.put("code", 0);
	         result.put("msg", "没有找到相应的红包订单");
	         return result;
		}else{
			if("0".equals(String.valueOf(list.get(0).get("PSTATE")))){
				 String updateSql = "update t_redenvdetail t set t.envstatus = '1' where t.remainid ="+redEnvId;
				 dao.updateBySql(updateSql);
				 result.put("code", 1);
		         result.put("msg", "操作成功");
			}else{
				 result.put("code", 0);
		         result.put("msg", "订单未支付");
		         return result;
			}
		}
        return result;
	}







	
}
